package com.toannv.handler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.smartfoxserver.bitswarm.sessions.ISession;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.exceptions.SFSErrorCode;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.exceptions.SFSLoginException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
import com.smartfoxserver.v2.extensions.ExtensionLogLevel;
import com.toannv.extension.LoginExtension;

public class LoginHandle extends BaseServerEventHandler {

	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException {
		// TODO Auto-generated method stub
		//grab parameters from client request
		String user = (String) event.getParameter(SFSEventParam.LOGIN_NAME);
		String pass = (String) event.getParameter(SFSEventParam.LOGIN_PASSWORD);
		ISession session = (ISession) event.getParameter(SFSEventParam.SESSION);
		
		//get password from database
		IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
		
		Connection connect;
		
		try{
			//get a connection to the database
			//Connection connect = getParentExtension().getParentZone().getDBManager().getConnection();
			connect = dbManager.getConnection();
			
			//create a prepare statement
			PreparedStatement sql = connect.prepareStatement("SELECT id, password FROM user WHERE user like '"+user+"'");
			sql.setString(1, user);
			
			//execute query of sql
			ResultSet result = sql.executeQuery();
			
			//verify that one record was found
			if(!result.first()){
				SFSErrorData err = new SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
				err.addParameter(user);
				
				throw new SFSLoginException("Bad user name"+user, err);
			}
			
			//put result to sfs object array
			SFSArray row = SFSArray.newFromResultSet(result);
			
			if(pass.equals("")){
				SFSErrorData data = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
				data.addParameter(user);
				throw new SFSLoginException("you must enter your password", data);
			}
			
			if (!getApi().checkSecurePassword(session, row.getSFSObject(0).getUtfString("password"), pass))
	           {
	                SFSErrorData data = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);

	                data.addParameter(user);

	                throw new SFSLoginException("Login failed for user: "  + user, data);
	            }
			
			if (user.equals("abc") || user.equals("tester"))
            {

                // Create the error code to send to the client
                SFSErrorData errData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
                errData.addParameter(user);

                // Fire a Login exception
                throw new SFSLoginException("abc and tester are not allowed in this Zone!", errData);
            }
			
			//get id of user
			int dbId = result.getInt("id");
			
			//store the id in the session
			session.setProperty(LoginExtension.DATABASE_ID, dbId);
			
			//close connect to database
			connect.close();
			
			trace("login successful, join zone.");
		}catch(SQLException ex){
			trace(ExtensionLogLevel.WARN, " SQL Failed: " + ex.toString());
		}
	}

}
